package org.rslai.tcedit.web.product;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.validator.InvalidStateException;
import org.hibernate.validator.InvalidValue;
import org.rslai.tcedit.domain.Page;
import org.rslai.tcedit.domain.Version;
import org.rslai.tcedit.exception.ApplicationException;
import org.rslai.tcedit.util.HttpUtil;
import org.rslai.tcedit.util.SessionUtil;
import org.rslai.tcedit.web.core.AbstractMvcController;

/**
 * 版本列表
 * @author rslai
 *
 * @spring.bean name="/product/versionList.jspx"
 */
public class VersionListController extends AbstractMvcController {

	@Override
	public Map<String, Object> getModel(HttpServletRequest request, HttpServletResponse response) throws Exception {
		int pageIndex = HttpUtil.getInt(request, "page", 0);

		String action = HttpUtil.getString(request, "action", "").toLowerCase();
		if (action.equals("search") && pageIndex==0) {
			Map<String, String> parametersMap = new HashMap<String, String>();
			parametersMap.put("page", "1");
			SessionUtil.setParametersSessionInfo(request, parametersMap);
		}

		Map<String, String> parametersMap = SessionUtil.getParametersSessionInfo(request);
		if (pageIndex==0) {
			pageIndex = Integer.parseInt(parametersMap.get("page"));
		} else {
			parametersMap.put("page", String.valueOf(pageIndex));
		}

		Page page = new Page(pageIndex);

		Map<String, Object> map = new HashMap<String, Object>();
		String productID = SessionUtil.getCurrentProductID(request);
		List<Version> version = null;

		try {
			if (productID.equals("")) {
				throw new ApplicationException("未选择产品，请先选择一个产品。");
			}
			version = versionService.query(productID, page, "%", true);

		} catch(Exception e) {
			map.put("error", convertException(e));
		}

		map.put("version", version);
		map.put("page", page);
		return map;
	}

	@Override
	public String getView(HttpServletRequest request, HttpServletResponse response) {
		return "/product/versionList.htm";
	}

	private String convertException(Exception e) throws Exception {
		if (e instanceof ApplicationException) {
			return e.getMessage();
		} else if (e instanceof InvalidStateException) {
			StringBuffer sb = new StringBuffer(128);
			InvalidValue[] ivs = ((InvalidStateException) e).getInvalidValues();
			for (InvalidValue iv : ivs)
				sb.append(iv.getMessage()).append("<br/>");
			return sb.toString();
		}
		throw e;
	}

}
